package cn.lingyangwl.framework.data.mate.fieldbind;

import cn.lingyangwl.framework.data.mate.fieldbind.inter.IDataBind;
import cn.lingyangwl.framework.data.mate.fieldbind.model.DictType;
import cn.lingyangwl.framework.data.mate.fieldbind.model.FieldBindAnnotationData;
import cn.lingyangwl.framework.tool.core.reflection.MetaObject;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author shenguangyang
 */
@Slf4j
public class DefaultDataBind implements IDataBind<Map<String, Map<String, String>>> {
    private static final Map<String, String> EMPTY_MAP = new HashMap<>();
    @Override
    public Map<String, Map<String, String>> getCodesOfTypes(List<DictType> dictTypes) {
        Map<String, Map<String, String>> defaultDictMap = new HashMap<>();
        for (DictType dictType : dictTypes) {
            Map<String, String> valueMap = new HashMap<>();
            valueMap.put("1", "1");
            valueMap.put("2", "2");
            valueMap.put("3", "3");
            defaultDictMap.put(dictType.getType(), valueMap);
        }
        return defaultDictMap;
    }

    @Override
    public void setMetaObject(MetaObject metaObject, Map<String, Map<String, String>> valuesOfTypes, Object fieldValue, FieldBindAnnotationData annotationData) {
        // 通过type或者对应的字典键值对, 然后通过 fieldValue = itemLabel, 或者对应的 itemValue
        Object value = this.assemblyTargetFieldValue(fieldValue, annotationData, code -> {
            String targetFieldValue = Optional.ofNullable(valuesOfTypes.get(String.valueOf(annotationData.getType())))
                    .orElse(EMPTY_MAP).get(String.valueOf(code));
            return Optional.ofNullable(targetFieldValue).orElse("");
        });
        metaObject.setValue(annotationData.getTarget(), value);
    }
}
